package com.se.Login;

import com.se.common.ConnectionType;
import com.se.common.Message;
import com.se.common.MessageType;
import com.se.common.User;
import com.se.utils.ClientConnectThread;
import com.se.utils.ServiceUtils;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 登录服务类 - 处理用户登录相关逻辑
 */

public class LoginService {
    private User user = new User();
    private Socket socket;

    /**
     * 校验用户登录
     * @return 登录状态（通过MessageType常量判断）
     */
    public String checkUserLogin(String username, String pwd) throws IOException,ClassNotFoundException {
        /*
        设置用户凭证
         */
        user.setUserName(username);
        user.setPassword(pwd);
        socket = new Socket(ServiceUtils.serverAddress, ServiceUtils.serverPort);
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

        Message loginMsg = new Message();
        loginMsg.setMsgType(MessageType.MESSAGE_LOGIN_REQUEST);
        loginMsg.setContent(user.toString());

        oos.writeObject(loginMsg);

        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        Message msg = (Message) ois.readObject(); // 阻塞等待响应

        String status = msg.getMsgType();
        if(MessageType.MESSAGE_LOGIN_SUCCESS.equals(status)){
            ClientConnectThread clientConnectThread = new ClientConnectThread(socket);
            clientConnectThread.start();
            ServiceUtils.addConnection(ConnectionType.BASE_CONNECTION,clientConnectThread);
            return status;
        }
        socket.close();
        return status;
    }
}
